﻿using Boco.CommonLib;
using DataSync.Common;
using DataSync.Entity;
using log4net;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace DataSync.Proc.Reader
{
    class FTPFileReader : FileDataReader
    {
        private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        FtpClient CurFtpClient;       //ftp操作
        private static object _lock = new object();
        FtpConfig CurFtpConf;  //ftp文件配置

        protected override void ReadSourceConfig(XElement xmlnode)
        {
            //读取配置
            var ftpconf = xmlnode;
            CurFtpConf = new FtpConfig(base.CurReaderConf);
            CurFtpConf.Type = "FTP";
            CurFtpConf.IP = ftpconf.GetAttribute("IP");
            CurFtpConf.Port = ftpconf.GetAttribute("Port");
            CurFtpConf.UserName = ftpconf.GetAttribute("UserName");
            CurFtpConf.Password = ftpconf.GetAttribute("Password");
            CurFtpConf.RemortDir = ftpconf.GetAttribute("RemortDir");
            CurFtpConf.FileMatch = ftpconf.GetAttribute("FileMatch");
            CurFtpConf.MaxDownLoadFile = ftpconf.GetAttributesAsInt("MaxDownLoadFile");

            CurFtpConf.RemortDir = CurFtpConf.RemortDir.Replace(@"$YYYY", DateTime.Now.AddDays(-1).ToString("yyyy"))
                .Replace(@"$MM", DateTime.Now.AddDays(-1).ToString("MM"))
                .Replace(@"$DD", DateTime.Now.AddDays(-1).ToString("dd"))
                .Replace(@"$HH", DateTime.Now.AddDays(-1).ToString("HH"));

            if (CurFtpConf.MaxDownLoadFile == 0)
            {
                CurFtpConf.MaxDownLoadFile = 10;
            }
            if (string.IsNullOrEmpty(CurFtpConf.FileMatch))
            {
                CurFtpConf.FileMatch = "*";
            }
        }

        public override void Close()
        {
            if (CurFtpClient != null)
            {
                CurFtpClient = null;
            }
            base.Close();
        }


        protected override List<string> GetFileList()
        {
            List<string> listFile = new List<string>();

            if (CurFtpClient == null)
            {
                CurFtpClient = new FtpClient(this.CurFtpConf);
            }

            string hasDownloadLogFile = GetFileHisLog();
            //下载文件
            listFile = CurFtpClient.SyncServerFile(hasDownloadLogFile);

            return listFile;
        }

        protected override void DeleteSourceFile(string file)
        {
            if (CurFtpClient == null)
            {
                CurFtpClient = new FtpClient(this.CurFtpConf);
            }
            CurFtpClient.DeleteFile(file);
        }
    }
}
